package main.java.com.silence.controller;

import com.silence.constant.AttributeConstant;
import com.silence.constant.ViewNameConstant;
import com.silence.pojo.Bill;
import com.silence.pojo.User;
import com.silence.service.IBillService;
import com.silence.vo.Pager;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Author: silence
 * Date: 17-6-2
 */
@Controller
public class MainController {

    @Resource
    private IBillService billService = null;

    /**
     * home页
     */

    @RequestMapping(value = "/home", method = RequestMethod.GET)
    public String homepage(){
        return "redirect:/home/1";
    }

    @RequestMapping(value = {"/home/{pageIndex}"}, method = RequestMethod.GET)
    public ModelAndView homePage(@PathVariable Integer pageIndex, HttpServletRequest request,
                                 ModelAndView modelAndView) throws ParseException {

        User user = (User) request.getSession().getAttribute(AttributeConstant.LOGIN_USER_INFO);

        if (pageIndex == null || pageIndex == 0)
            pageIndex = 1;

        Pager<Bill> pager;
        Date createDate;

        // 如果传入了查询条件 -- 创建日期
        if (request.getParameter("createDate") != null && !request.getParameter("createDate").equals("")){

            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");//小写的mm表示的是分钟

            createDate = sdf.parse(request.getParameter("createDate"));

            modelAndView.addObject("createDate", createDate);
            pager = billService.findAllByOwnerEmailAndCreateDate(user.getEmail(), pageIndex, createDate);
        } else {
            // 没有传入查询条件 -- 创建日期

            pager = billService.findAllByOwnerEmail(user.getEmail(), pageIndex);
        }
        modelAndView.addObject(AttributeConstant.PAGER, pager);

        modelAndView.setViewName(ViewNameConstant.HOME);

        return modelAndView;
    }
}
